package com.lagou.edu.service.impl;

import com.lagou.edu.config.EmailConfig;
import com.lagou.edu.service.SendEmailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.regex.Pattern;

/**
 * @date 2020/5/26 18:24
 */
@Slf4j
@Service
public class SendEmailServiceImpl implements SendEmailService {

    @Autowired
    EmailConfig emailConfig;

    Pattern emailPattern = Pattern.compile("^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,})");

    @Override
    public Boolean sendEmail(String emailAddress, String code) {
        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(emailAddress)){
            return false;
        }
        if (!checkEmail(emailAddress)){
            return false;
        }
        try{
            //发送邮件
            HtmlEmail emailClient = new HtmlEmail();
            emailClient.setHostName(emailConfig.getHostname());
            emailClient.setCharset("UTF-8");
            //接受者的邮箱地址
            emailClient.addTo(emailAddress);
            //发件人邮箱、姓名
            emailClient.setFrom(emailConfig.getUsername(), emailConfig.getName());
            //发件人账户、密码
            emailClient.setAuthentication(emailConfig.getUsername(), emailConfig.getPassword());
            //邮箱主题
            emailClient.setSubject(emailConfig.getTheme());
            emailClient.setHtmlMsg("【拉勾教育】验证码：" + code + ", " + emailAddress + " 您正在使用邮箱认证。有效期为：5分钟");
            emailClient.send();
            return true;
        }catch (Exception e){
            log.error(e.getMessage());
            return false;
        }
    }

    private boolean checkEmail(String email){
        return emailPattern.matcher(email).matches();
    }

}
